package com.ls.lserp.modules.setting.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.setting.entity.CompanyList;
import com.ls.lserp.modules.setting.entity.Duty;
import com.ls.lserp.modules.setting.entity.WarehouseShelves;
import com.ls.lserp.modules.setting.service.WarehouseShelvesService;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.entity.Sequence;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.UserUtils;

import groovy.util.ResourceException;

/**
 * @ClassName: WarehouseShelvesController
 * @Description:
 * 
 * @author 许天航
 * @date 2017年01月09日
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/warehouse/message/")
public class WarehouseShelvesController extends BaseController {

	@Autowired
	private WarehouseShelvesService warehouseShelvesService;
	
	@ModelAttribute
	public WarehouseShelves get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return warehouseShelvesService.findByID(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new WarehouseShelves();
		}
	}
	

	/**
	 * 仓库一览画面
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = { "" })
	public String warehouseshelves() {

		return "modules/setting/warehouseShelves";

	}

	/**
	 * 拼接一览画面
	 * @param values 
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("warehouse:message:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(WarehouseShelves warehouseShelves, HttpServletRequest request, HttpServletResponse response,
			Model model, String[] values) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		FileUtils filUtils = new FileUtils();
		DateFormat dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		// ajax回调时使用的一览list名
		request.setAttribute("listNames", "warehouse");
		// 画面取得的检索项目
		String warehouseCode = warehouseShelves.getWarehouseCode();
		String warehouseName = warehouseShelves.getWarehouseName();
		String warehouseType = warehouseShelves.getWarehouseType();
		String strUri = request.getContextPath() + Global.getAdminPath();

		// 拼接字符串供分页使用
		String searchParam = "&warehouseCode=" + warehouseCode+"&warehouseName=" + warehouseName+"&warehouseType=" + warehouseType;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		// 查询一览页面数据
		Page<WarehouseShelves> page = warehouseShelvesService.findWarehouseList(new Page<WarehouseShelves>(request, response),
				warehouseShelves);
		// 读取系统路径
		String basePath = SystemPath.getClassPath();
		String tempFilePath = "//"+ basePath + "templates//demoHtml//warehouseList.txt";
		// 读取文件生成字符串
		String warehouseHtml = readTxtFile(tempFilePath);
		String createUser = "";
		String strHtml = "";
		int pageNo = 0;
		if (!"".equals(warehouseHtml)) {
			for (int i = 0; i < page.getList().size(); i++) {
				warehouseHtml = filUtils.readFileToHtml(tempFilePath);
				// 画面No
				pageNo = (page.getPageNo() - 1) * page.getPageSize() + (i + 1);
				warehouseHtml = warehouseHtml.replace("pageNo", "" + pageNo);
				// 分类仓库代码
				warehouseHtml = warehouseHtml.replace("warehouseCode",
						StringUtils.checkStringNull(page.getList().get(i).getWarehouseCode()));
				// 分类仓库名称
				warehouseHtml = warehouseHtml.replace("warehouseName",
						StringUtils.checkStringNull(page.getList().get(i).getWarehouseName()));
				String warehouseline = "\"popup('800px','519px','" + strUri + "/warehouse/message/viewWarehouse?id="
						+ page.getList().get(i).getId() + "&editFlag=0')\"";
				// 分类id
				warehouseHtml = warehouseHtml.replace("warehouseId", warehouseline);
				// 分类仓库类别
				warehouseHtml = warehouseHtml.replace("warehouseTypeCn",
						StringUtils.checkStringNull(page.getList().get(i).getWarehouseTypeCn()));
				// 分类仓库条形码
				warehouseHtml = warehouseHtml.replace("warehouseBarCodeVal",
						StringUtils.checkStringNull(page.getList().get(i).getWarehouseBarCode()));
				// 分类仓库位置
				warehouseHtml = warehouseHtml.replace("warehousePlace", StringUtils.checkStringNull(page.getList().get(i).getWarehousePlace()));
				// 分类备注
				warehouseHtml = warehouseHtml.replace("warehouseRemark", StringUtils.checkStringNull(page.getList().get(i).getWarehouseRemark()));
				// 分类状态
				String status = page.getList().get(i).getWarehouseStatus();
				if ("1".equals(status)) {
					status = SystemMessageUtils.getMessageName( "warehouse_open");
				}else{
					status = SystemMessageUtils.getMessageName( "warehouse_close");
				}
				warehouseHtml = warehouseHtml.replace("warehouseStatus",
						StringUtils.checkStringNull(status));
				// 创建人
				createUser = StringUtils.checkStringNull(page.getList().get(i).getCreateBy().getFirstName());
				warehouseHtml = warehouseHtml.replace("createUser", createUser);
				// 创建日期
				dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Date createDate = page.getList().get(i).getCreateDate();
				warehouseHtml = warehouseHtml.replace("createDate", dateForamat.format(createDate));
				strHtml += warehouseHtml;
			}
		}
		listMap.put("warehouse", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}

	/**
	 * 获取货架代码和货架条形码
	 * 
	 * @return
	 */
	@RequiresPermissions("warehouse:message:view")
	@ResponseBody
	@RequestMapping(value = "getCode")
	public String getCode(WarehouseShelves warehouseShelves,HttpServletResponse response) {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		warehouseShelves.setCreateBy(UserUtils.getUser());
    	WarehouseShelves userMessege =  warehouseShelvesService.userMessege(warehouseShelves);
		//公司国别
    	//Dict dictCountry=DictUtils.getDictEntity(userMessege.getCompanyCountry());
    	//公司地区
    	//Dict dictCity=DictUtils.getDictEntity(userMessege.getCompanyCity());
    	//公司简称
    	String companyShortName=userMessege.getCompanyShortName().toUpperCase();
		//楼层位置
        String sPlace= warehouseShelves.getShelvesPlace();
        
        StringBuilder sCode = new StringBuilder();
        //sCode.append(dictCountry.getItemShortNameEn());
       // sCode.append(dictCity.getItemShortNameEn());
        sCode.append(companyShortName);
        sCode.append(sPlace);
        
        // 仓库货架编号
        Sequence sSequence=SequenceUtil.ognizationCode(sCode.toString(), "sequence_shelves", 6);
        String shelvesBarCode = SequenceUtil.shelvesbarcode().getReturnCode();
        listMap.put("shelvesCode", sCode.toString());
        listMap.put("shelvesBarCode", shelvesBarCode);
		return renderString(response, listMap);

	}
	
	/**
	 * 获取仓库代码和仓库条形码
	 * 
	 * @return
	 */
	@RequiresPermissions("warehouse:message:view")
	@ResponseBody
	@RequestMapping(value = "getWarehouseCode")
	public String getWarehouseCode(WarehouseShelves warehouseShelves,HttpServletResponse response) {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		warehouseShelves = warehouseShelvesService.getWarehouseCode(warehouseShelves);
        listMap.put("warehouseCode", warehouseShelves.getWarehouseCode());
        listMap.put("warehouseBarCode", warehouseShelves.getWarehouseBarCode());
		return renderString(response, listMap);

	}
	
	/**
	 * 创建仓库信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("warehouse:message:view")
	@RequestMapping(value = "createWarehouse")
	public String createWarehouse(WarehouseShelves warehouseShelves, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		model.addAttribute("warehouseShelves", warehouseShelves);
		return "modules/setting/createWarehouse";

	}

	/**
	 * 编辑仓库信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("warehouse:message:view")
	@RequestMapping(value = "editWarehouse")
	public String editWarehouse(WarehouseShelves warehouseShelves, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String flag = warehouseShelves.getEditFlag();
		warehouseShelves = warehouseShelvesService.findAWarehouse(warehouseShelves);		
		warehouseShelves.setEditFlag(flag);
		model.addAttribute("warehouseShelves", warehouseShelves);
		return "modules/setting/createWarehouse";

	}

	

	/**
	 * 创建编辑保存仓库信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("warehouse:message:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(WarehouseShelves warehouseShelves, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
		if(warehouseShelves.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			WarehouseShelves warehouseShelvesNew = get(warehouseShelves.getId().toString());
			// 判断数据是否删除
            if(warehouseShelvesNew==null || BaseEntity.DEL_FLAG_DELETE.equals(warehouseShelvesNew.getDeleteFlag())){
            	// 返回提示信息
            	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
            }
			
            // 排他处理
		    if(warehouseShelves.getVersion()==get(warehouseShelves.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	warehouseShelves.setVersion(warehouseShelves.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		    	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
		    }
		}
			
			
		    // 保存数据
			warehouseShelvesService.saveWarehouse(warehouseShelves);
			
			// 保存成功返回提示信息
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "warehouse_edit_save_msg_success")));
			
			
	}
	/**
	 * 删除仓库信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("warehouse:message:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public String delete(WarehouseShelves warehouseShelves, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
				if(warehouseShelves.getId()!=null){
					// 编辑数据
					// 判断数据是否删除
					WarehouseShelves warehouseShelvesNew = get(warehouseShelves.getId().toString());
					// 判断数据是否删除
		            if(warehouseShelvesNew==null || BaseEntity.DEL_FLAG_DELETE.equals(warehouseShelvesNew.getDeleteFlag())){
		            	// 返回提示信息
		            	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
		            }
					
		            // 排他处理
				    if(warehouseShelves.getVersion()==get(warehouseShelves.getId().toString()).getVersion()){
				    	
				    	// 版本号加1
				    	warehouseShelves.setVersion(warehouseShelves.getVersion()+1);
				    }else{
				    	
				    	// 返回提示信息
				    	return renderString(response,AjaxDone.error(getText("warehouse_edit_delete_msg_fail")));
				    }
				}
					
					
				    // 保存数据
					warehouseShelvesService.deleteWarehouse(warehouseShelves);
					
					// 保存成功返回提示信息
					return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "warehouse_edit_delete_msg_success")));
					

	}		
			
		


	/**
	 * 查看一条仓库信息
	 * 
	 * @return
	 */
	@RequiresPermissions("warehouse:message:view")
	@RequestMapping(value = "viewWarehouse")
	public String viewWarehouse(WarehouseShelves warehouseShelves, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String flag = warehouseShelves.getEditFlag();
		warehouseShelves = warehouseShelvesService.findAWarehouse(warehouseShelves);
		
		warehouseShelves.setEditFlag(flag);
		model.addAttribute("warehouseShelves", warehouseShelves);
		return "modules/setting/createWarehouse";

	}

	/**
	 * 添加仓库货架
	 * 
	 * @return
	 */

	@RequestMapping(value = "addShelves")
	public String addShelves(WarehouseShelves warehouseShelves, HttpServletRequest request, HttpServletResponse response,
			Model model) {		

		model.addAttribute("warehouseShelves", warehouseShelves);
		return "modules/setting/addShelves";

	}

}